<template>
	<view>
		<view>
			<view>
				<view class='header'>
					<text>智慧园区</text>
				</view>
				<view v-if="!userInfo ">
					<view class='content'>
						<view>申请获取以下权限</view>
						<text>获得你微信昵称和头像</text>
					</view>
					
					<button class='bottom' type='primary' @click="getUserInfo">
						授权头像
					</button>
				</view>
				<view v-else>
					<view class='content'>
						<view>申请获取以下权限</view>
						<text>获得你微信绑定的手机号</text>
					</view>
					
					<button class='bottom' type='primary' open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
						手机号登录
					</button>
					
					<!-- <button class='bottom youke'  >
						游客登录
					</button> -->
				</view>
				
				<!-- <button class='bottom' style="margin-top: 20rpx;" type='primary' open-type="getPhoneNumber" @getphonenumber="getPhoneNumber2">
					云函数手机号登录
				</button> -->
			</view>
		</view>
	</view>
</template>

<script>
	// import login from '@/api/login.js'
	// import crypto from '@/utils/crypto'
	// import store from '@/store'
	import * as api from '../../api/methods'
	var that;
	export default {
		data() {
			return {
				appCode: "",
				userInfo: {},
				
			}
		},
		onLoad() {
			that = this
			
			// if (this.$store.state.isCrypto) {
			// 	if (!uni.getStorageSync('rsaPk')) {
			// 		this.$getPublicKey()
			// 	}
			// } 
			this.login()
		},
		
		methods: {
			login() {
				uni.login({
					provider: 'weixin',
					success: async (loginRes) => {
						console.log('!!!! loginRes', loginRes)
						that.appCode = loginRes.code;
						// that.getUserInfo()
					},
					fail: (error) => {
						console.log('error', error)
					}
				});
			},
			getUserInfo() {
				uni.getUserProfile({ 
					lang: 'zh_CN',
					desc:'获取用户信息',
					success: userInfo => {
						console.log('userInfo', userInfo);
						if (userInfo.errMsg == 'getUserProfile:ok') {
							that.userInfo = userInfo.userInfo
							// that.getPhoneNumber()
						} else {
						}
					 },
					fail:err=>{
						console.log(err,'err')
					}
				});
			},
			// getPhoneNumber2(e){
			// 	console.log('getPhoneNumber2 '+JSON.stringify( e) )
			// 	wx.cloud.init({ // 初始化云开发环境
			// 	          traceUser: true,
			// 	          env: 'jkbpweex-1gj0ro2qafa8e1a6'
			// 	        })
			// 	wx.cloud.callFunction({
			// 		name:'getphone',
			// 		data:{
			// 			cloudId: e.detail.cloudID
			// 		}
			// 	}).then(res =>{
			// 		console.log('云函数手机号 '+ JSON.stringify( res) )
			// 		// this.setData({
			// 		// 	showPhone:res.result.list[0].data.phoneNumber
			// 		// })
			// 		var encryptedData = e.detail.encryptedData;
			// 		var iv = e.detail.iv;
			// 		var code = e.detail.code;
			// 		var nickName = '';//that.userInfo.nickName;
			// 		var headImg = '';//that.userInfo.avatarUrl;
			// 		var phone = '';
			// 		if(res.result && res.result.list[0] && res.result.list[0].data){
			// 			phone = res.result.list[0].data.phoneNumber
			// 		}
					
			// 		let canshu = '&phone='+ phone +'&channelCode=10010&encryptedData='+encryptedData +'&iv='+iv+'&code='+code //+'&headImg='+headImg+'&nickName='+encodeURIComponent(nickName)
			// 		uni.redirectTo({
			// 			url:'/pages/webview/webview?url=user'+canshu
			// 		})
			// 	})
			// },
			toParams(param) {
			    var result = ""
			    for (let name in param) {
			        if (typeof param[name] != 'function') {
			            result += "&" + name + "=" + encodeURI(param[name]);
			        }
			    }
			    return result.substring(1)
			},
			getPhoneNumber(e) {
				console.log("phone",e)
				wx.checkSession({
					success: async function() {
						var ency = e.detail.encryptedData; //.replace('+','%2B')
						var iv = e.detail.iv;//.replace('+','%2B')
						var code = that.appCode;
						var nickName = that.userInfo.nickName;
						var headImg = that.userInfo.avatarUrl;
						if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
							uni.showToast({
								title: '请允许获取你的手机号码，否则部分功能无法使用',
								mask: true,
								icon: 'none'
							})
						} else { //同意授权
							// let reqData = {
							// 	encryptedData: ency,
							// 	iv: iv,
							// 	code: code,
							// 	nickName: nickName,
							// 	headImg: headImg,
							// 	channelCode: '10002'
							// }
							//jkbpuser2022080500514480 乐乐茶 dev环境
							//jkbpuser2022082200482509 农银金科测试园区 test 环境
							//jkbpuser2022081100469003 生产环境
							let canshu = 'orgId='+ api.getOrgId() +'&channelCode=10010&encryptedData='+ency +'&iv='+iv+'&code='+code //+'&headImg='+headImg+'&nickName='+encodeURIComponent(nickName)
							// console.log('@@@@ canshu '+ canshu) //到这里是ok的
							canshu = canshu.replace(' ','+')
							let url = '/pre?'+ canshu
							// console.log('@@@@ url '+ url) //到这里是ok的
							// uni.redirectTo({
							// 	url:'/pages/webview/webview?url=user'+canshu
							// })
							let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
							let prevPage = pages[ pages.length - 2 ];
							// url = 'https://static-b355b199-f26f-4bea-b13c-1b2c8fff663f.bspapp.com/webview_h5/pm_h5.html'
							prevPage.$vm.setUrl(url)
							uni.navigateBack()
							
							// const [err, res] = await login.loginMini(reqData);
							// // 根据结果进行处理
							// console.log('err', err)
							// console.log('res', res)
							// if (res) {
							// 	uni.setStorageSync('token', res.token)
							// 	uni.setStorageSync('userId', res.userId)
							// 	uni.switchTab({
							// 		url:'/pages/index/index',
							// 		success:(res)=> {
							// 		}
							// 	});
							// 	// 动态底部导航菜单
							// 	// 如果使用动态底部菜单无法使用switchTab；使用reLaunch关闭全部的页面，打开新的栏目页面
							// 	// uni.reLaunch({
							// 	// 	url: '/pages/index/index'
							// 	// });
							// } else {
							// 	console.log("授权失败");
							// }
						}
					},
					fail: () => {
						console.log("登录已超时，请重新登录");
						this.login(); //重新登录
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.header {
		padding: 100rpx 0 60rpx 0;
		text-align: center;
		width: 100%;
		height: 300rpx;
		line-height: 300rpx;
		font-size: 50rpx;
	}

	.content {
		margin-left: 60rpx;
		margin-bottom: 50rpx;
	}
	
	.content view{
		font-size: 38rpx;
	}

	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 36rpx;
	}

	.bottom {
		border-radius: 80rpx;
		margin: 0 50rpx;
		font-size: 35rpx;
	}

	.bottom:first-child {
		margin-top: 50rpx;
	}

	.view_input {
		margin: 0 50rpx;
		background-color: white;
		padding: 10px;
		height: 1rem;
		line-height: 1rem;
	}
	.youke{
		margin-top: 20px;
	}
</style>
